package com.tornado.community.controller;

import com.tornado.community.dto.QuestionDto;
import com.tornado.community.mapper.custome.MyQuestionMapper;
import com.tornado.community.provider.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class IndexController {
    private final MyQuestionMapper myQuestionMapper;
    private final Tools tools;

    @Autowired
    public IndexController(MyQuestionMapper myQuestionMapper, Tools tools) {
        this.myQuestionMapper = myQuestionMapper;
        this.tools = tools;
    }

    @GetMapping("/")
    public String index(@RequestParam(name = "page", defaultValue = "1") Integer page,
                        @RequestParam(name = "size", defaultValue = "5") Integer size,
                        Model model, HttpServletRequest request) {
        tools.loginCheck(request);
        int offset = size * (page - 1);
        List<QuestionDto> questionList = myQuestionMapper.selectQuestionList(offset, size);
        double pageCount = (myQuestionMapper.count() * 1.0) / size;
        model.addAttribute("questionList", questionList);
        model.addAttribute("page", page);
        model.addAttribute("pageCount", (int) Math.ceil(pageCount));
        return "index";
    }
}
